Python 시작하기

이 노트북은 처음으로 Python을 시작하는 사람이 실제로 명령어를 실행시키면서 기본 개념을 익히기 위한 문서이다.


In [1]:
print("Hello, world!")


Hello, world!
  • python 2

    • print 1
  • python 3

    • print(1)
  • python 2에서 python 3 문법을 사용하려면

    • from __future__ import print_function
    • 본 강의에서는 python 3 문법 사용

In [2]:
a = 3
b = 2 * a

In [3]:
a
b


Out[3]:
6

Basic Types 기본 자료형

  • Boolean 부울리언
  • Integer 정수
  • Float 부동소수점
  • Complex 복소수
  • None

Boolean 부울리언


In [4]:
True, False


Out[4]:
(True, False)

In [5]:
test = (3 > 4)
test


Out[5]:
False

In [6]:
type(test)


Out[6]:
bool

Integer 정수


In [7]:
a = 4

In [8]:
type(a)


Out[8]:
int

Float 부동소수점


In [9]:
c = 2.1

In [10]:
type(c)


Out[10]:
float

Complex 복소수


In [11]:
a = 1.5 + 0.5j
a


Out[11]:
(1.5+0.5j)

In [12]:
a.real


Out[12]:
1.5

In [13]:
a.imag


Out[13]:
0.5

In [14]:
type(1. + 0j)


Out[14]:
complex

Casting 자료형 변환


In [15]:
float(1)


Out[15]:
1.0

In [16]:
7 * 3.


Out[16]:
21.0

Division


In [17]:
from __future__ import division

In [18]:
3 / 2


Out[18]:
1.5

In [19]:
# without from __future__ import division
# 3 / 2   =>  1

In [20]:
3 // 2


Out[20]:
1

Power


In [21]:
2**10


Out[21]:
1024

Modulo


In [22]:
8 % 3


Out[22]:
2

Assignment


In [23]:
a = 1
a += 1
a


Out[23]:
2

In [24]:
a = 1
a -= 1
a


Out[24]:
0

In [25]:
a = 10
a *= 2
a


Out[25]:
20

In [26]:
a = 10
a /= 2
a


Out[26]:
5.0

Comparison 비교

$$ 2 > 1, \;\;\; 2 \geq 1, \;\;\; 2 = 1 $$

In [27]:
2 > 1, 2 >= 1, 2 == 1


Out[27]:
(True, True, False)

Containers 고급 자료형

  • list 리스트
  • dictionary 사전
  • tuple 튜플
  • string 문자열

List 리스트


In [28]:
l = ['red', 'blue', 'green', 'black', 'white']
type(l)


Out[28]:
list

Indexing 인덱싱

  • container 유형의 자료에서 일부 자료만 뽑아내는 일

In [29]:
l[0]


Out[29]:
'red'

In [30]:
l[1]


Out[30]:
'blue'

In [31]:
l[-1]


Out[31]:
'white'

In [32]:
l[-2]


Out[32]:
'black'

Slicing 슬라이싱


In [33]:
l[2:4]


Out[33]:
['green', 'black']
  • l[start:stop:step]
    • start<= < stop
    • i = i + step
  • All slicing parameters are optional:

In [34]:
l[2:]


Out[34]:
['green', 'black', 'white']

In [35]:
l[:2]


Out[35]:
['red', 'blue']

In [36]:
l[::2]


Out[36]:
['red', 'green', 'white']
  • Lists are mutable
  • can be modified

In [37]:
l


Out[37]:
['red', 'blue', 'green', 'black', 'white']

In [38]:
l[0] = 'yellow'
l


Out[38]:
['yellow', 'blue', 'green', 'black', 'white']

In [39]:
l[2:4] = ['gray', 'purple']
l


Out[39]:
['yellow', 'blue', 'gray', 'purple', 'white']
  • list may have different types

In [40]:
l = [3.14, -200, 'hello']

In [41]:
l[1], l[2]


Out[41]:
(-200, 'hello')

Methods 메소드

  • Add, Remove

In [42]:
L = ['red', 'blue', 'green', 'black', 'white']

In [43]:
L.append('pink')

In [44]:
L


Out[44]:
['red', 'blue', 'green', 'black', 'white', 'pink']

In [45]:
L.pop() # removes and returns the last item


Out[45]:
'pink'

In [46]:
L


Out[46]:
['red', 'blue', 'green', 'black', 'white']

In [47]:
L.extend(['pink', 'purple']) # extend L, in-place

In [48]:
L


Out[48]:
['red', 'blue', 'green', 'black', 'white', 'pink', 'purple']

In [49]:
L = L[:-2]
L


Out[49]:
['red', 'blue', 'green', 'black', 'white']
  • Reverse

In [50]:
r = L[::-1]
r


Out[50]:
['white', 'black', 'green', 'blue', 'red']

In [51]:
r.reverse()

In [52]:
r


Out[52]:
['red', 'blue', 'green', 'black', 'white']

In [53]:
r2 = list(L)
r2


Out[53]:
['red', 'blue', 'green', 'black', 'white']

In [54]:
r2.reverse() # in-place
r2


Out[54]:
['white', 'black', 'green', 'blue', 'red']
  • Concatenate and repeat lists

In [55]:
r + L


Out[55]:
['red',
 'blue',
 'green',
 'black',
 'white',
 'red',
 'blue',
 'green',
 'black',
 'white']

In [56]:
r


Out[56]:
['red', 'blue', 'green', 'black', 'white']

In [57]:
r * 2


Out[57]:
['red',
 'blue',
 'green',
 'black',
 'white',
 'red',
 'blue',
 'green',
 'black',
 'white']
  • Sort

In [58]:
sorted(r) # new object


Out[58]:
['black', 'blue', 'green', 'red', 'white']

In [59]:
r


Out[59]:
['red', 'blue', 'green', 'black', 'white']

In [60]:
r.sort()  # in-place

In [61]:
r


Out[61]:
['black', 'blue', 'green', 'red', 'white']
  • All methods
    • r. + press

In [62]:
r.


  File "<ipython-input-62-ea092d2967a4>", line 1
    r.
      ^
SyntaxError: invalid syntax

In [63]:
dir(r)


Out[63]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__delslice__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__setslice__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

String 문자열


In [64]:
s = 'Hello, how are you?'
s


Out[64]:
'Hello, how are you?'
  • Multi-line string

In [65]:
s = '''Hello,                 
       how are you'''
s


Out[65]:
'Hello,                 \n       how are you'

In [66]:
s = """Hi,
what's up?"""
s


Out[66]:
"Hi,\nwhat's up?"

In [67]:
s = 'Hi, what's up?'


  File "<ipython-input-67-1b11fbf9496e>", line 1
    s = 'Hi, what's up?'
                  ^
SyntaxError: invalid syntax
  • nested

In [68]:
s = "Hi, what's up?"
s


Out[68]:
"Hi, what's up?"
  • string is a container

In [69]:
a = "hello"

In [70]:
a[0]


Out[70]:
'h'

In [71]:
a[1]


Out[71]:
'e'

In [72]:
a[-1]


Out[72]:
'o'

In [73]:
a = "hello, world!"

In [74]:
a[3:6]


Out[74]:
'lo,'

In [75]:
a[2:10:2]


Out[75]:
'lo o'

In [76]:
a[::3]


Out[76]:
'hl r!'
  • immutable: cannot change

In [77]:
a[2] = 'z'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-77-d57c4312feba> in <module>()
----> 1 a[2] = 'z'

TypeError: 'str' object does not support item assignment

In [ ]:
a.replace('l', 'z')

In [78]:
a


Out[78]:
'hello, world!'
  • format
    • string % argument
    • %d: integer
    • %f: float
    • %s: string

In [79]:
"x=%d" % 1


Out[79]:
'x=1'

In [80]:
"%s=%f" % ("pi", 3.14)


Out[80]:
'pi=3.140000'

Dictionary 사전


In [81]:
tel = {'emmanuelle': 5752, 'sebastian': 5578}
tel


Out[81]:
{'emmanuelle': 5752, 'sebastian': 5578}

In [82]:
tel['sebastian']


Out[82]:
5578

In [83]:
tel['francis'] = 5915
tel


Out[83]:
{'emmanuelle': 5752, 'francis': 5915, 'sebastian': 5578}

In [84]:
tel.keys()


Out[84]:
['sebastian', 'francis', 'emmanuelle']

In [85]:
tel.values()


Out[85]:
[5578, 5915, 5752]

In [86]:
'francis' in tel


Out[86]:
True

Tuple 튜플


In [87]:
u = (0, 2)
u


Out[87]:
(0, 2)

In [88]:
t = 12345, 54321, 'hello!'
t


Out[88]:
(12345, 54321, 'hello!')

In [89]:
t[0]


Out[89]:
12345

In [90]:
b[0] = 1


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-90-d28c64b6d9cf> in <module>()
----> 1 b[0] = 1

TypeError: 'int' object does not support item assignment

Reference, Mutable, Immutable


In [91]:
a = [1, 2, 3]
b = a

In [92]:
a


Out[92]:
[1, 2, 3]

In [93]:
b


Out[93]:
[1, 2, 3]

In [94]:
id(a), id(b)


Out[94]:
(139806688343608, 139806688343608)

In [95]:
a[0] = 11

In [96]:
a


Out[96]:
[11, 2, 3]

In [97]:
b


Out[97]:
[11, 2, 3]

In [ ]:


In [98]:
b[1] = 'hi!'

In [99]:
b


Out[99]:
[11, 'hi!', 3]

In [100]:
a


Out[100]:
[11, 'hi!', 3]

In [101]:
a = [1, 'hi!', 3]

In [102]:
b = 1

In [103]:
id(a), id(b)


Out[103]:
(139806689796752, 9666936)

zip


In [104]:
a = [1, 2, 3]
b = [10, 20, 30]

In [105]:
c = zip(a, b)
c


Out[105]:
[(1, 10), (2, 20), (3, 30)]

In [106]:
d = dict(c)
d


Out[106]:
{1: 10, 2: 20, 3: 30}

In [107]:
zip(*c)


Out[107]:
[(1, 2, 3), (10, 20, 30)]

In [108]:
zip(*zip(*c))


Out[108]:
[(1, 10), (2, 20), (3, 30)]

Code Line-Break 여러 줄로 나누어 쓰기

  • 리스트나 딕셔너리 정의, 함수 호출/정의 등의 경우에는 문법적으로 완료되지 않으면 그냥 다음 줄 사용 가능
  • 그렇지 않은 경우 backslash사용

In [109]:
a = [1, 2, 3,
     4, 5, 6]
a


Out[109]:
[1, 2, 3, 4, 5, 6]

In [110]:
a = 1 + 3 + 4 +
    5 + 6 + 7


  File "<ipython-input-110-4f831cc21792>", line 1
    a = 1 + 3 + 4 +
                   ^
SyntaxError: invalid syntax

In [111]:
a = 1 + 3 + 4 + \
    5 + 6 + 7
a


Out[111]:
26

Control Flow 흐름 제어

  • if/elif/else
  • for/range
  • while/break/continue
  • enumerate
  • dictionary loop
  • list comprehension

If/elif/else


In [112]:
if 2**2 == 4:
    print('Obvious!')


Obvious!
  • Python Indentation 들여쓰기
    • space or tab
    • number of spaces: block level
    • convention: 4 spaces

In [113]:
a = 10
if a == 1:
    print(1)
elif a == 2:
    print(2)
else:
    print('A lot')


A lot

for/range


In [114]:
range(10)   # :10


Out[114]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [115]:
for i in range(4):
    print(i)


0
1
2
3

In [116]:
i


Out[116]:
3

In [117]:
range(5, 10)  # 5:10


Out[117]:
[5, 6, 7, 8, 9]

In [118]:
x = ["a", "b", "c", "d", "e"]
for i in range(1, 4):
    print(x[i])


b
c
d

In [119]:
for word in ['cool', 'powerful', 'readable']:
    print('Python is %s' % word)


Python is cool
Python is powerful
Python is readable

In [120]:
for xi in x[1:4]:
    print(xi)


b
c
d

In [121]:
print(x[1:4])


['b', 'c', 'd']

while/break/continue


In [122]:
z = 1 + 1j
while abs(z) < 100:
    z = z**2 + 1
    print(z, abs(z))
z


(1+2j) 2.2360679775
(-2+4j) 4.472135955
(-11-16j) 19.4164878389
(-134+352j) 376.643067107
Out[122]:
(-134+352j)

In [123]:
z = 1 + 1j
while abs(z) < 100:
    if z.imag < 0:
        print("break!")
        break
    z = z**2 + 1
    print(z)
z


(1+2j)
(-2+4j)
(-11-16j)
break!
Out[123]:
(-11-16j)

In [124]:
a = [1, 0, 2, 4]
for element in a:
    if element == 0:
        continue
    print(1. / element)


1.0
0.5
0.25

Enumerate


In [125]:
words = ('cool', 'powerful', 'readable')
for i in range(len(words)):
    print((i, words[i]))


(0, 'cool')
(1, 'powerful')
(2, 'readable')

In [126]:
for i, item in enumerate(words):
    print((i, item))


(0, 'cool')
(1, 'powerful')
(2, 'readable')

Dictionary Loop


In [127]:
d = {'a': 1, 'b':1.2, 'c':1j}
d.items()


Out[127]:
[('a', 1), ('c', 1j), ('b', 1.2)]

In [128]:
for key, val in sorted(d.items()):
    print('Key: %s has value: %s' % (key, val))


Key: a has value: 1
Key: b has value: 1.2
Key: c has value: 1j

In [129]:
for item in sorted(d.items()):
    print('item:', str(item))


item: ('a', 1)
item: ('b', 1.2)
item: ('c', 1j)

List Comprehensions


In [130]:
%%timeit
x = range(10000)
y = []
for i in x:
    y.append(i * 2)


1000 loops, best of 3: 835 µs per loop

In [131]:
%%timeit
y = [i*2 for i in range(10000)]


1000 loops, best of 3: 498 µs per loop

Function 함수

  • definition 정의
  • parameter 인수
  • local, global 스코프
  • variable number of parameters
  • docstring

definition 함수의 정의

  • 콜론(:) 사용
  • 들여쓰기 (indentation)

In [132]:
def test():
    print('in test function')

In [133]:
test()


in test function

In [134]:
test()
test()
test()
test()


in test function
in test function
in test function
in test function

parameter 인수


In [135]:
def disk_area(radius):
    return 3.14 * radius * radius

In [136]:
disk_area(1.5)


Out[136]:
7.0649999999999995

In [137]:
def double_it(x):
    return x * 2

In [138]:
double_it(3)


Out[138]:
6

In [139]:
double_it()


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-139-51cdedbb81b0> in <module>()
----> 1 double_it()

TypeError: double_it() takes exactly 1 argument (0 given)

default parameter


In [2]:
def double_it(x=2):
    return x * 2

In [3]:
double_it(3)


Out[3]:
6

In [4]:
double_it()


Out[4]:
4

In [5]:
def slicer(seq, start=None, stop=None, step=None):
    return seq[start:stop:step]

In [6]:
rhyme = 'one fish, two fish, red fish, blue fish'.split()
rhyme


Out[6]:
['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']

In [7]:
slicer(rhyme)  # rhyme[::]


Out[7]:
['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']

In [8]:
slicer(rhyme, step=2) # rhyme[::2]


Out[8]:
['one', 'two', 'red', 'blue']

In [9]:
slicer(rhyme, 1, step=2) # rhyme[1::2]


Out[9]:
['fish,', 'fish,', 'fish,', 'fish']

In [10]:
slicer(rhyme, start=1, stop=4, step=2) # rhyme[1:4:2]


Out[10]:
['fish,', 'fish,']

local variable


In [11]:
def try_to_modify(x, y, z):
    x = 23
    y.append(42)
    z = [99] # new reference
    print(x)
    print(y)
    print(z)

In [12]:
a = 77    # immutable variable
b = [99]  # mutable variable
c = [28]

In [13]:
try_to_modify(a, b, c)


23
[99, 42]
[99]

In [14]:
print(a)
print(b)
print(c)


77
[99, 42]
[28]

In [15]:
x = 5
def addx(y):
    return x + y

In [16]:
addx(10)


Out[16]:
15

In [17]:
def setx(y):
    x = y
    print('x is %d' % x)

In [18]:
setx(10)


x is 10

In [19]:
x


Out[19]:
5

global variable


In [20]:
def setx(y):
    global x
    x = y
    print('x is %d' % x)

In [21]:
setx(10)


x is 10

In [22]:
x


Out[22]:
10

Variable number of parameters

  • *args: positional arguments (tuple)
  • **kwargs: keyword arguments (dictionary)

In [23]:
def variable_args(*args, **kwargs):
    print('args is', args)
    print('kwargs is', kwargs)

In [24]:
variable_args('one', 'two', x=1, y=2, z=3)


args is ('one', 'two')
kwargs is {'y': 2, 'x': 1, 'z': 3}

Docstrings


In [25]:
def funcname(params):
    """Concise one-line sentence describing the function.
    Extended summary which can contain multiple paragraphs.
    """
    pass

In [26]:
funcname??

In [27]:
funcname.__doc__


Out[27]:
'Concise one-line sentence describing the function.\n    Extended summary which can contain multiple paragraphs.\n    '

None

  • 아무것도 출력하지 않거나
  • 아무것도 받지 않는 경우

In [28]:
def f():
    a = 1

In [29]:
x = f()
x

In [30]:
print(x)


None

is 비교

  • 같은 메모리를 가리키고 있는지 비교

In [31]:
a = 3.14 * 2
b = 6.28

In [32]:
a == b


Out[32]:
True

In [33]:
print(id(a), id(b))


65719224 65719272

In [34]:
a is b


Out[34]:
False

In [35]:
a = None

In [36]:
# a == None <---  사용하지 말것! __eq__ overload 시 위험!
a is None, a is not None


Out[36]:
(True, False)

In [37]:
def f(x, y=None):
    if y is None:
        return x * x
    else:
        return x * y

In [38]:
f(10)


Out[38]:
100

In [39]:
f(10, 20)


Out[39]:
200

Package Import


In [40]:
import scipy

In [41]:
scipy.__file__


Out[41]:
'/home/joel/anaconda2/lib/python2.7/site-packages/scipy/__init__.pyc'
  • pakage alias
    • 패키지 이름이 길거나 다른 이름으로 사용하고 싶은 경우
    • import XXX as YY

In [42]:
import numpy as np
import scipy as sp
import pandas as pd
import sklearn as sk
import matplotlib as mpl
import matplotlib.pylab as plt
import seaborn as sns
  • 서브패키지 임포트

    • 자동 임포트

      • 상위 패키지를 임포트 하면 상위 패키지의 __init__.py 내부에서 하위 패키지를 임포트
      • 사용자가 하위 패키지를 추가로 임포트할 필요 없음
    • 수동 임포트

      • 메모리 절약을 위해 하위 패키지를 자동으로 임포트 하지 않음
      • 사용자가 필요한 서브패키지를 수동으로 임포트

In [43]:
sp.stats.norm.rvs(size=10)


Out[43]:
array([ 0.15060943, -0.23652534, -0.51602361, -0.7335559 , -1.35747775,
        1.87101961,  0.12348571,  0.53643438,  1.70221398,  0.55901586])

In [44]:
sp.constants.c


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-44-1041528b4e47> in <module>()
----> 1 sp.constants.c

AttributeError: 'module' object has no attribute 'constants'

In [45]:
import scipy.constants
sp.constants.c


Out[45]:
299792458.0